import { compatibilityTree } from './compatibility-tree';
import fs from 'fs';
import path from 'path';

/**
 * 工程聚合器 - 提供简洁的工程入口
 */
export class ProjectAggregator {
  private static instance: ProjectAggregator;
  private mode: 'development' | 'production' = 'development';

  private constructor() {}

  public static getInstance(): ProjectAggregator {
    if (!ProjectAggregator.instance) {
      ProjectAggregator.instance = new ProjectAggregator();
    }
    return ProjectAggregator.instance;
  }

  /**
   * 设置运行模式
   */
  public setMode(mode: 'development' | 'production') {
    this.mode = mode;
    console.log(`Switched to ${mode} mode`);
  }

  /**
   * 获取简洁工程结构
   */
  public getSimplifiedStructure() {
    const baseDir = process.cwd();
    const simplified = {
      // 1. 版本化核心 (始终可见)
      'Core Modules': this.getVersionedStructure('src'),
      'Tests': this.getVersionedStructure('test'),
      
      // 2. 兼容层配置
      'Compatibility Layer': {
        'env.json': 'Runtime configuration',
        'proto': 'Protocol definitions'
      },
      
      // 3. 开发模式额外信息
      ...(this.mode === 'development' ? {
        'Configuration': this.getConfigStructure(),
        'Tooling': {
          'scripts': 'Build/maintenance scripts',
          '.vscode': 'IDE configuration'
        },
        'System Files': [
          'package.json',
          'tsconfig.json',
          'Dockerfile'
        ]
      } : {
        'Note': 'Run in development mode to view full structure'
      })
    };

    return simplified;
  }

  private getVersionedStructure(dir: string) {
    const structure: Record<string, any> = {};
    const basePath = path.join(process.cwd(), dir);

    if (fs.existsSync(basePath)) {
      fs.readdirSync(basePath).forEach(module => {
        const modulePath = path.join(basePath, module);
        if (fs.lstatSync(modulePath).isDirectory()) {
          structure[module] = this.mode === 'development' ? 
            fs.readdirSync(modulePath) : 
            `v${compatibilityTree.treeStructure.code[module]}`;
        }
      });
    }

    return structure;
  }

  private getConfigStructure() {
    const configs: Record<string, any> = {};
    const configPath = path.join(process.cwd(), '.config');

    if (fs.existsSync(configPath)) {
      fs.readdirSync(configPath).forEach(tool => {
        const toolPath = path.join(configPath, tool);
        if (fs.lstatSync(toolPath).isDirectory()) {
          configs[tool] = fs.readdirSync(toolPath);
        }
      });
    }

    return configs;
  }

  /**
   * 一键运行工程
   */
  public runProject() {
    console.log('Starting project in', this.mode, 'mode...');
    
    // 1. 确保兼容层就绪
    this.ensureCompatibilityLayer();
    
    // 2. 加载环境配置
    this.loadEnvironment();
    
    // 3. 启动主程序
    this.startMainProcess();
  }

  private ensureCompatibilityLayer() {
    const layerPath = path.join(process.cwd(), 'compatibility-layer');
    if (!fs.existsSync(layerPath)) {
      throw new Error('Compatibility layer not initialized. Run `npm run compat:tree` first.');
    }
  }

  private loadEnvironment() {
    const envPath = path.join(process.cwd(), 'compatibility-layer', 'env.json');
    if (fs.existsSync(envPath)) {
      const env = JSON.parse(fs.readFileSync(envPath, 'utf-8'));
      process.env.PROJECT_ENV = JSON.stringify(env);
    }
  }

  private startMainProcess() {
    // 这里应该是项目特定的启动逻辑
    // 示例：启动核心模块的默认版本
    const mainModule = compatibilityTree.getCompatiblePath('src/core/main.ts');
    if (fs.existsSync(mainModule)) {
      require(mainModule);
    } else {
      console.log('Project started successfully. Ready for development!');
    }
  }
}

// 导出单例实例
export const projectAggregator = ProjectAggregator.getInstance();